import React from 'react';
import { BaseEditorProps } from '../editors/BaseEditor';
import { InputEditor } from '../editors/InputEditor';
import { SelectEditor } from '../editors/SelectEditor';
import { EditableExcelTableProps, SelectColumn, TColumn } from '../types/public';

/**
 * 默认的只读渲染函数
 * 根据列类型提供合适的只读显示方式
 */
function renderDefaultReadonly<C extends TColumn = TColumn>(value: string, column: C): React.ReactNode {
    switch (column.type) {
        case 'select':
        case 'text':
            if (typeof value !== 'string') return value;
            const htmlString = value.split('\n').reduce((str, text) => {
                return str + text + '<br />';
            }, '');

            return <div data-edit="isedit" dangerouslySetInnerHTML={{ __html: htmlString }} />;
        default:
            return <div data-edit="default-edit">{value || ''}</div>;
    }
}

interface SelectEditorOptions<C extends TColumn = TColumn> {
    column: C;
    editorProps: BaseEditorProps<C>;
    editorRenderers?: EditableExcelTableProps['editorRenderers'];
    isReadonly?: boolean;
}

/**
 * 根据列类型选择对应的编辑器组件
 * 这是从 CellEditor 和 TopEditorBar 中抽取的公用逻辑
 */
export function selectEditorByType<C extends TColumn = TColumn>(options: SelectEditorOptions<C>): React.ReactNode {
    const { column, editorProps, editorRenderers, isReadonly = false } = options;

    // 优先使用自定义编辑器渲染器
    if (editorRenderers?.[column.type]) {
        const renderer = editorRenderers[column.type];

        if (renderer) {
            if (isReadonly && renderer.readonlyRender) {
                const ReadonlyRender = renderer.readonlyRender;
                // 使用只读渲染器
                return <ReadonlyRender value={editorProps.value} />;
            } else if (renderer.editableRender) {
                // 使用可编辑渲染器
                const EditableRender = renderer.editableRender;
                return (
                    <EditableRender
                        value={editorProps.value}
                        onClose={editorProps?.onClose ?? (({}) => {})}
                        className={editorProps?.className ?? ''}
                        // 改变过程的值，如果没有提供，则不触发和顶部的共享数据
                        onChange={editorProps?.onChange ?? (() => {})}
                    />
                );
            }
        }
    }

    // 如果是只读模式且没有自定义渲染器，提供默认的只读渲染
    if (isReadonly) {
        return renderDefaultReadonly(editorProps.value, column);
    }

    // 根据列类型选择内置编辑器
    switch (column.type) {
        case 'select':
            return <SelectEditor {...editorProps} column={column as SelectColumn} />;
        case 'text':
        default:
            return <InputEditor {...editorProps} />;
    }
}
